package com.jindun.paper.ui.bag;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;

import com.jindun.paper.model.Order;

public class OrderListViewFilter  extends ViewerFilter {

	private List<Integer> clientIds;
	
	private Date startDate;
	
	private Date endDate;
	

	public OrderListViewFilter () {
		clientIds = new ArrayList<Integer>();
		
		Calendar current = Calendar.getInstance();
		current.setTime(new Date ());
		this.endDate = current.getTime();
		
		
		current.add(Calendar.MONTH, -1);
		this.startDate = current.getTime();
		
		
	}
	
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public List<Integer> getClientIds() {
		return clientIds;
	}

	public void setClientIds(List<Integer> clientIds) {
		this.clientIds = clientIds;
	}

	@Override
	public boolean select(Viewer viewer, Object parentElement, Object element) {
		boolean matched = false;
		Order bagOrder = (Order)element;
		if (clientIds != null && !clientIds.isEmpty()) {
			for (Integer clientId : clientIds) {
				if (bagOrder.getClient().getId().equals(clientId)) {
					matched = true;
					break;
				}
			}
		} else {
			matched = true;
		}
		
		return matched && this.isBetween(bagOrder.getCreateDate(), startDate, endDate);
	}
	
	private boolean isBetween (Date date, Date startDate, Date endDate) {
		Date temp = DateUtils.truncate(date, Calendar.DATE);
		startDate =  DateUtils.truncate(startDate, Calendar.DATE);
		endDate =  DateUtils.truncate(endDate, Calendar.DATE);
		return (temp.before(endDate) && temp.after(startDate)) || temp.equals(startDate) || temp.equals(endDate);
 	}
	
}
